package com.hy.chanping.product.user.service.impls;

import com.cqsudu.lightning.boot.jpa.SpecificationBuilder;
import com.cqsudu.lightning.boot.time.DateFormatUtil;
import com.cqsudu.lightning.service.core.Result;
import com.hy.chanping.product.core.user.dtos.SimpleUser;
import com.hy.chanping.product.core.user.dtos.User;
import com.hy.chanping.product.core.user.dtos.UserCreate;
import com.hy.chanping.product.core.user.services.UserService;
import com.hy.chanping.product.user.daos.UserRepository;
import com.hy.chanping.product.user.models.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springside.modules.utils.mapper.BeanMapper;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public SimpleUser findOne(Long id) {
        Optional<UserEntity> optional = userRepository.findById(id);
        return optional.map(userEntity -> BeanMapper.map(userEntity, SimpleUser.class)).orElse(null);
    }

    @Override
    public List<SimpleUser> findSimpleByIds(List<Long> ids) {
        List<UserEntity> entities = userRepository.findAllById(ids);
        return BeanMapper.mapList(entities, UserEntity.class,  SimpleUser.class);
    }

    @Override
    public Long create(UserCreate user) {
        UserEntity entity = new UserEntity();
        entity.setRealName(user.getRealName());
        entity.setMobile(user.getMobile());
        entity.setCreatedAt(new Date());
        userRepository.save(entity);
        return entity.getId();
    }

    @Override
    public Result<User> page(String name, @NotNull Integer page, @NotNull Integer size) {
        PageRequest pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
        Specification<UserEntity> specification = SpecificationBuilder.builder(UserEntity.class)
                .like("realName", "%" + name + "%")
                .and();

        Page<UserEntity> entityPage = userRepository.findAll(specification, pageRequest);
        List<UserEntity> entities = entityPage.getContent();
        List<User> users = BeanMapper.mapList(entities, UserEntity.class, User.class);
        users.forEach(item -> item.setCreatedAtStr(DateFormatUtil.formatDate(DateFormatUtil.PATTERN_DEFAULT_ON_SECOND, item.getCreatedAt())));
        return Result.page(users, entityPage.getTotalElements());
    }
}
